package cn.changeforyou.web.dao.mybatis.ext.extBuilder.writer;

import cn.changeforyou.web.dao.mybatis.ext.dao.BaseDao;
import cn.changeforyou.web.dao.mybatis.ext.extBuilder.SqlContext;
import cn.changeforyou.web.dao.mybatis.ext.extBuilder.sqlUtils.ColumnsUtils;
import cn.changeforyou.web.dao.mybatis.ext.extBuilder.sqlUtils.WhereUtils;
import cn.changeforyou.web.dao.mybatis.ext.metaInfo.FieldMetaInfo;
import cn.changeforyou.web.dao.mybatis.ext.metaInfo.condition.ConditionType;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author zhyu
 * @version 1.0
 * @date 2022/3/26 22:39
 */

@Component
public class SetSqlWriter extends AbstractSqlWriter{

    @Override
    void doWriteSql(SqlContext context) {
        List<FieldMetaInfo> updateMetaInfo = context.getUpdateMetaInfo();
        SqlBuilder sql = context.getSql();
        sql.append("\n  <set>");
        for (FieldMetaInfo fieldMetaInfo : updateMetaInfo) {
            sql.append("\n      ");
            writeByFieldMetaInfo(fieldMetaInfo, context);
        }

        sql.append("\n</set>");
    }

    @Override
    public SentenceEnum getSentenceEnum() {
        return SentenceEnum.set;
    }

    private void writeByFieldMetaInfo(FieldMetaInfo fieldMetaInfo, SqlContext context) {
        SqlBuilder sql = context.getSql();
        if(context.isUpdateIgnoreNull()) {
            WhereUtils.buildIfTestPrefix(context, fieldMetaInfo);
        }

        ColumnsUtils.writeColumnsInSelectSentence(sql, fieldMetaInfo);
        String currentJavaParamPrefix = context.getCurrentJavaParamPrefix();
        WhereUtils.buildWhereExpressionOperatorBody(sql, ConditionType.equal, fieldMetaInfo.getFieldName(), currentJavaParamPrefix);
        sql.append(",");

        if(context.isUpdateIgnoreNull()) {
            WhereUtils.buildIfTestPostfix(context);
        }
    }
}
